package com.txby.platformApi.component.web;

import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.http.HttpEntity;
import org.apache.http.NameValuePair;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;
import org.apache.log4j.Logger;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import com.alibaba.fastjson.JSONObject;
import com.jck.mybatis.util.PageBean;
import com.jck.mybatis.util.PageList;
import com.jck.tools.ChkUtil;
import com.txby.platformCore.component.service.CommonController;
import com.txby.platformCore.component.util.YoukuVideoUtils;
import com.txby.platformCore.data.CommonApiModelMapExt;
import com.txby.platformCore.entity.News;
import com.txby.platformCore.entity.Video;

import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;

/**
 * 新闻和视频处理入口类
* @author lzq
* @date  
 */
@SuppressWarnings("all")
@RestController
@Api(value="新闻",description="新闻-说明")
@RequestMapping("/news")
public class NewsController extends CommonController{
	private static Logger log = Logger.getLogger(NewsController.class);
	@ApiOperation(value = "查询新闻列表", notes = "查询新闻列表-说明")
/*	@ApiImplicitParams({
		@ApiImplicitParam(paramType="query",dataType="number",name="type",value="请求端（ 0:web,1:android,2:iphone）",required=true),
		@ApiImplicitParam(paramType="query",dataType="string",name="token",value="用户令牌",required=true),
		@ApiImplicitParam(paramType="query",dataType="string",name="newsType",value="新闻类别（默认全部类别，1：院内2：行业3：通知）",required=true),
		@ApiImplicitParam(paramType="query",dataType="string",name="beginTime",value="新闻创建时间",required=false),
		@ApiImplicitParam(paramType="query",dataType="string",name="endTime",value="新闻创建时间",required=false),
		@ApiImplicitParam(paramType="query",dataType="string",name="searchContent",value="模糊搜索内容",required=false),
		@ApiImplicitParam(paramType="query",dataType="string",name="curPage",value="当前页，默认1",required=false),
		@ApiImplicitParam(paramType="query",dataType="string",name="pageSize",value="页大小，默认10",required=false)
	})*/
//	@GlobalLogAnnotation(logType=2,discription="患者查询类别新闻")
	@GetMapping("/getNewsInfoList/{type}/{token}")
	public CommonApiModelMapExt getNewsInfoList(@PathVariable("type") Integer type, @PathVariable("token") String token,String newsType,Integer pageSize,Integer curPage ) {
		CommonApiModelMapExt mm = chekTokenCahceValid(token, type);
		isTokenValid=true;
		try {
			if (!isTokenValid) {
				return mm;
			}
			// 业务必须字段非空校验
			if(newsType==null || ChkUtil.isEmpty(newsType)) {
				mm.put(CommonApiModelMapExt.ERRCODE, 1);
				mm.put(CommonApiModelMapExt.ERRMSG, "请求参数有误");
				return mm;
			}
			Map paramMap = new HashMap<>();
			String searchSql = "";
			if (!ChkUtil.isEmpty(newsType)) {
				searchSql += " and newsType = #{pojo.newsType} ";
				paramMap.put("newsType",  newsType);
			}
			searchSql += " order by publishTime desc";// 时间倒序排序
			PageList pl=new PageList<>();
			PageBean pb = new PageBean();
			if(!ChkUtil.isEmpty(curPage)) {
				pb.setCurrentPage(curPage);
			} 
			if(!ChkUtil.isEmpty(pageSize)) {
				pb.setPageSize(pageSize);
			} 
			pl = this.mBaseDao.findBySqlForPageList("select newsId,url,title,subhead,author,publishTime,pageviews,content from  "+mBaseDao.tableName(News.class)+" where 1=1  "+searchSql, Map.class, pb, paramMap);
		   
			List l = pl.getResultList();
			for(Object o:l) {
				Map m = (Map)o;
				System.out.println(m.get("url"));
			}
			/**
			 * 请求http数据api
			 */
			mm.put(CommonApiModelMapExt.ERRCODE, 0);
			mm.put(CommonApiModelMapExt.ERRMSG, "查询成功");
			mm.put("data", pl.getResultList());
			return mm;
			
		} catch (Exception e) {
			e.printStackTrace();
			mm.put(CommonApiModelMapExt.ERRCODE, 5000);
			mm.put(CommonApiModelMapExt.ERRMSG, "系统异常");
		}
		
		return mm;
	}
	
//	@GlobalLogAnnotation(logType=2,discription="查询单个新闻")
	@GetMapping("/getNewsInfo/{type}/{token}")
	public CommonApiModelMapExt getNewsInfo(@PathVariable("type") Integer type, @PathVariable("token") String token,Integer newsId) {
		CommonApiModelMapExt mm = chekTokenCahceValid(token, type);
		try {
			if (!isTokenValid) {
				return mm;
			}
			// 业务必须字段非空校验
			if(ChkUtil.isEmpty(newsId)) {
				mm.put(CommonApiModelMapExt.ERRCODE, 1);
				mm.put(CommonApiModelMapExt.ERRMSG, "请求参数有误");
				return mm;
			}
			Map paramMap = new HashMap<>();
			String searchSql = "";
			if (!ChkUtil.isEmpty(newsId)) {
				searchSql += " and newsId = #{pojo.newsId} ";
				paramMap.put("newsId",  newsId);
			}
			searchSql += " order by publishTime desc";// 时间倒序排序
			Object news=(Object) this.mBaseDao.findBySqlUniqueObject("update "+mBaseDao.tableName(News.class) + " set pageviews = pageviews+1 where 1=1  ", News.class,null);
			 news= (Object) this.mBaseDao.findBySqlUniqueObject("select newsId,title,subhead,author,publishTime,pageviews,content from "+mBaseDao.tableName(News.class) + " where 1=1  "+searchSql, News.class,paramMap);
			/**
			 * 请求http数据api
			 */
			mm.put(CommonApiModelMapExt.ERRCODE, 0);
			mm.put(CommonApiModelMapExt.ERRMSG, "查询成功");
			mm.put("data", news);
			return mm;
			
		} catch (Exception e) {
			e.printStackTrace();
			mm.put(CommonApiModelMapExt.ERRCODE, 1);
			mm.put(CommonApiModelMapExt.ERRMSG, "系统异常");
		}
		
		return mm;
	}
	
	
	/**
	 * 查询患教视频
	 */
	@GetMapping("/getSickVideoJson/{type}/{token}")
	public CommonApiModelMapExt getSickVideoJson(@PathVariable("type") Integer type, @PathVariable("token") String token,Integer pageSize,Integer curPage, String sort) throws Exception {
		CommonApiModelMapExt mm =  chekTokenCahceValid(token, type);
		try {
			if (!isTokenValid) {
				return mm;
			}
			Map paramMap = new HashMap<>();
			String searchSql = "";
			if (!ChkUtil.isEmpty(sort) && !"0".equals(sort)) {
				searchSql += " and sort = #{pojo.sort} ";
				paramMap.put("sort",  sort);
			}
			searchSql += " order by published desc";// 时间倒序排序
			PageList pl=new PageList<>();
			PageBean pb = new PageBean();
			if(!ChkUtil.isEmpty(curPage)) {
				pb.setCurrentPage(curPage);
			} 
			if(!ChkUtil.isEmpty(pageSize)) {
				pb.setPageSize(pageSize);
			} 
			pl = this.mBaseDao.findBySqlForPageList("select * from  "+mBaseDao.tableName(Video.class)+" where 1=1 and state='published'  "+searchSql, Map.class, pb, paramMap);
			if(pl==null || pl.getResultList()==null || pl.getResultList().size()==0) {
				mm.put(CommonApiModelMapExt.ERRCODE, 4500);
				mm.put(CommonApiModelMapExt.ERRMSG, "查询成功");
				mm.put("data", pl.getResultList());
				return mm;
			}
			Map videos = new HashMap();
			videos.put("videos", pl.getResultList());
			videos.put("count", pl.getResultList().size());
			mm.put(CommonApiModelMapExt.ERRCODE, 0);
			mm.put(CommonApiModelMapExt.ERRMSG, "查询成功");
			mm.put("data", videos);
			return mm;
			
		} catch (Exception e) {
			e.printStackTrace();
			mm.put(CommonApiModelMapExt.ERRCODE, 1);
			mm.put(CommonApiModelMapExt.ERRMSG, "系统异常");
		}
		return mm;
	}
	

	@GetMapping("/saveToLocal/{type}/{token}")
	public CommonApiModelMapExt saveToLocal(@PathVariable("type") String type, @PathVariable("token") String token) {
		CommonApiModelMapExt mm = new CommonApiModelMapExt();
		// list
		CloseableHttpClient httpClient =YoukuVideoUtils.createSSLClientDefault();   
		HttpGet httpGet=null;
		CloseableHttpResponse response = null;
		List<NameValuePair> params=new ArrayList<NameValuePair>();
		params.add(new BasicNameValuePair("client_id",YoukuVideoUtils.CLIENT_ID));
		params.add(new BasicNameValuePair("access_token",YoukuVideoUtils.getLatestToken()));
		params.add(new BasicNameValuePair("page", "1"));
		params.add(new BasicNameValuePair("count","50"));
		try {
			httpGet= YoukuVideoUtils.getHttpGet("https","api.youku.com",-1,"/videos/by_me.json",params,null);
			response = httpClient.execute(httpGet);
			HttpEntity entity =response.getEntity();
			String html=EntityUtils.toString(entity);
			Map m = (Map) JSONObject.parseObject(html,Map.class);
			int total = (int) m.get("total");
			int pages = total % 50 == 0 ? total/50 : (total/50)+1;
			for(int i=1;i<=pages;i++) {
				params.add(new BasicNameValuePair("page", String.valueOf(i)));
				httpGet= YoukuVideoUtils.getHttpGet("https","api.youku.com",-1,"/videos/by_me.json",params,null);
				response = httpClient.execute(httpGet);
				entity =response.getEntity();
				html=EntityUtils.toString(entity);
				m = (Map) JSONObject.parseObject(html, Map.class);
				List list = (List) m.get("videos");
				for (Object obj:list) {
					Map map = (Map)obj;
					map.put("operation_limit", null);
					map.put("streamtypes", null);
					Video video = new Video();
					video.setVideoId(map.get("id")+"");
					video.setTitle(map.get("title")+"");
					video.setLink(map.get("link")+"");
					video.setThumbnail(map.get("thumbnail")+"");
					video.setBigthumbnail(map.get("bigThumbnail")+"");
					video.setCategory(map.get("category")+"");
					video.setState(map.get("state")+"");
					video.setDuration((Double.valueOf(map.get("duration")+"")));
					video.setTags(map.get("tags")+"");
					video.setView_count((Integer)map.get("view_count"));
					video.setPublished(map.get("published")+"");
					video.setPublic_type(map.get("public_type")+"");
//					BeanCusUtils.copyProperties(video, map);
					this.mBaseDao.saveObject(video);
				}
			}
			mm.put(CommonApiModelMapExt.ERRCODE, 0);
			mm.put(CommonApiModelMapExt.ERRMSG, "保存成功");
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			//关闭连接
			try {
				response.close();
				httpClient.close();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
		return mm;
	}
}